import Konva from "konva";
import { ref, reactive } from "vue";
import s0 from "@/assets/other/idp/computer.png";
import s1 from "@/assets/other/idp/macbook.png";
import s2 from "@/assets/other/idp/printer.png";
import s3 from "@/assets/other/idp/usb.png";
import s4 from "@/assets/other/idp/camera.png";
import s5 from "@/assets/other/idp/router.png";
import { string } from "vue-types";

export const currentOption = {
  node: {} as any, //当前正在编辑的节点
  org: {} as any, //当前页面对应的部门
  orgPic: string
};

// 拖动元素时将被拖拽的对象保存到内存中
export function dragStartEvent(e) {
  e.dataTransfer.setData("Text", e.target.id);
}
// 阻止浏览器的默认行为，允许拖拽
export function dragoverEvent(e) {
  e.preventDefault();
}
export const deviceList = ref<any[]>([]);

const GroupIndex = ref(1);
export const formDialog = ref(false);
export const forRef = ref();
export const form = reactive({
  id: "",
  deviceTpye: "",
  url: ""
});

export const tipVisible = ref(false);

// 将元素拖拽到 canvas 中时的事件，
export function dropEvent(e, layer) {
  e.preventDefault();
  const imgId = e.dataTransfer.getData("Text");
  const imageObj = new Image();
  imageObj.src = loadTopoImg(imgId);
  const darthVaderImg = new Konva.Image({
    image: imageObj,
    width: 40,
    height: 40,
    name: "topoImg",
    x: e.layerX - 20,
    y: e.layerY - 20
  });
  darthVaderImg.setAttr("imgType", imgId);

  const group = new Konva.Group({
    id: "g" + GroupIndex.value,
    draggable: true,
    hostData: {}
  });
  GroupIndex.value++;
  group.add(darthVaderImg);
  // 设置鼠标样式
  group.on("mouseover", function (e) {
    document.body.style.cursor = "pointer";
    if (typeof e.target.parent.attrs.deviceData == "string") {
      const deviceData = JSON.parse(e.target.parent.attrs.deviceData);
      console.log(deviceData);
      tipVisible.value = true;
    }
  });
  group.on("mouseout", function () {
    document.body.style.cursor = "default";
    tipVisible.value = false;
  });

  // 右键点击进入模态框编辑节点
  group.on("click", e => {
    console.log("左键单机", e);
    currentOption.node = e.target;
    formDialog.value = true;
  });
  // 移动节点时同步调整连接线的起始位置
  group.on("dragmove", function (e) {
    console.log(e);
  });
  group.on("dblclick", function (e) {
    console.log(e.target);
  });
  layer.add(group);
}

// 加载 拓扑图 需要使用到的图片资源
function loadTopoImg(imgId) {
  switch (imgId) {
    case "tuoputu_computer":
      return s0;
    case "tuoputu_macbook":
      return s1;
    case "tuoputu_printer":
      return s2;
    case "tuoputu_usb":
      return s3;
    case "tuoputu_camera":
      return s4;
    case "tuoputu_router":
      return s5;
    default:
      return s3;
  }
}

// 提交表单
export const commitForm = () => {
  currentOption.node.parent.setAttr("deviceData", JSON.stringify(form));
  formDialog.value = false;
  console.log(currentOption.node.parent.getAttr("deviceData"));
};
